package com.c39.otc.open.launcher;

import com.c39.otc.open.api.AppSessionTemplate;
import com.cqfan.cloud.framework.base.context.ApplicationContextProvider;
import com.cqfan.cloud.framework.global.LogicI18nException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: JiaLing.Fan
 * @Date: 2022/11/28 22:03
 * @Description:
 */
@Slf4j
public class OpenInterceptor implements HandlerInterceptor {

    /**
     * 访问控制器方法前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String accessToken = request.getHeader("accessToken");

        log.info("----{request}:" + request.getRequestURI());

        String requestURI = request.getRequestURI();
        if (StringUtils.isEmpty(accessToken)) {
            log.error("----{AccessToken为空}");
            throw new LogicI18nException("10", "Token校验失败");
        }

        AppSessionTemplate appSessionTemplate = ApplicationContextProvider.applicationContext.getAutowireCapableBeanFactory().getBean(AppSessionTemplate.class);
        String sessionId = appSessionTemplate.get(accessToken);
        if(!accessToken.equals(sessionId)){
            throw new LogicI18nException("10", "Token校验失败");
        }
        return true;
    }

    /**
     * 访问控制器方法后执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    /**
     * postHandle方法执行完成后执行，一般用于释放资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        AppSessionTemplate appSessionTemplate = ApplicationContextProvider.applicationContext.getAutowireCapableBeanFactory().getBean(AppSessionTemplate.class);
        appSessionTemplate.currentThreadremove();
    }
}
